import { _decorator, Button, Component, Label, Node } from 'cc';
import { DataManager } from '../DataManager';
const { ccclass, property } = _decorator;

@ccclass('ChooseRoleController')
export class ChooseRoleController extends Component {
  @property(Label)
  role1: Label | null = null;
  @property(Label)
  role2: Label | null = null;
  @property(Button)
  submitBtn: Button | null = null;
  @property(Node)
  waitingNode: Node | null = null;

  selectedRole: string = '';

  start() {}

  onDestroy() {
    this.stopInputEvent();
  }

  openWaiting() {
    this.waitingNode.active = true;
  }
  closeWaiting() {
    this.waitingNode.active = false;
  }

  open() {
    this.closeWaiting();
    this.selectedRole = DataManager.instance.role || 'client-1';
    switch (this.selectedRole) {
      case 'client-1':
        this.role1.enableOutline = true;
        this.role2.enableOutline = false;
        break;
      case 'client-2':
        this.role1.enableOutline = false;
        this.role2.enableOutline = true;
        break;
    }
    this.node.active = true;
    this.startInputEvent();
  }
  close() {
    this.openWaiting();
    this.node.active = false;
    this.stopInputEvent();
  }

  startInputEvent() {
    this.role1.node.on(Node.EventType.MOUSE_DOWN, () => {
      this.role1.enableOutline = true;
      this.role2.enableOutline = false;
      this.selectedRole = 'client-1';
    });
    this.role2.node.on(Node.EventType.MOUSE_DOWN, () => {
      this.role1.enableOutline = false;
      this.role2.enableOutline = true;
      this.selectedRole = 'client-2';
    });
    this.submitBtn.node.on(Button.EventType.CLICK, () => {
      if (this.selectedRole) {
        this.selectRole(this.selectedRole);
      }
    });
  }
  stopInputEvent() {
    this.submitBtn.node.off(Button.EventType.CLICK);
    this.role1.node.off(Node.EventType.MOUSE_DOWN);
    this.role2.node.off(Node.EventType.MOUSE_DOWN);
  }

  selectRole(role: string) {
    console.log('选择角色:', role);
    DataManager.instance.GameManager.selectRole(role);
    this.close();
  }

  update(deltaTime: number) {}
}
